import http from './http'

declare global {
  interface Window {
    wx?: any
    WeixinJSBridge?: any
  }
}

/**
 * 微信授权登录
 * 跳转到微信授权页面
 * @returns {Promise<void>} 无返回值
 */
export async function wxAuth() {
  const { data } = await http.get(
    `/api/[project]/highway/wxAuth?url=${window.location.href}`,
  )
  window.location.href = data
}

/**
 * 判断当前环境是否为微信浏览器
 * @returns {boolean} 是否为微信浏览器
 */
export function isWeixin(): boolean {
  const ua = window.navigator.userAgent.toLowerCase()
  return !!ua.match(/micromessenger/i)
}

/**
 * 初始化微信 JS-SDK 配置
 * @param {object} options - 分享配置项
 * @param {string} options.title - 分享标题
 * @param {string} options.desc - 分享描述
 * @param {string} options.link - 分享链接
 * @param {string} options.imgUrl - 分享图片
 * @returns {Promise<void>} 无返回值
 */
export async function initWXConfig(options?: {
  title?: string
  desc?: string
  link?: string
  imgUrl?: string
}) {
  if (!isWeixin())
    return

  const { data } = await http.get(
    `/api/project/jssdk?url=${encodeURIComponent(window.location.href)}`,
  )
  const { wx } = window

  wx?.config({
    debug: false,
    appId: data.appId,
    timestamp: data._wxTimestamp,
    nonceStr: data._wxNoncestr,
    signature: data._wxSignature,
    jsApiList: [
      'onMenuShareAppMessage',
      'onMenuShareTimeline',
      'updateAppMessageShareData',
      'updateTimelineShareData',
    ],
  })

  wx?.ready(() => {
    const shareData = {
      title: '这里是分享标题， 请提供',
      desc: '这里是分享描述，请提供',
      link: window.location.origin,
      imgUrl: `${window.location.origin}/share.png`,
      ...options,
    }

    wx.onMenuShareAppMessage(shareData)
    wx.onMenuShareTimeline(shareData)
    wx.updateAppMessageShareData(shareData)
    wx.updateTimelineShareData(shareData)

    window.WeixinJSBridge.call('showOptionMenu')
  })
  wx?.error((error: any) => {
    console.warn('wx.error is', error)
  })
}

/**
 * 预加载图片资源
 * @param {string[]} paths - 需要预加载的图片路径数组
 * @returns {Promise<boolean|Event>} 加载成功返回true，失败返回错误事件
 */
export async function PreLoadImages(paths: string[]) {
  let imageFetchCount: number = 0
  return new Promise((resolve) => {
    paths.forEach((path: string) => {
      const i = new Image()
      i.src = path
      i.onload = function () {
        imageFetchCount++
        if (imageFetchCount >= paths.length) {
          resolve(true)
        }
      }

      i.onerror = function (e) {
        resolve(e)
      }
    })
  })
}

/**
 * 获取assets目录下所有图片资源的路径
 * @returns {string[]} 图片路径数组
 */
export function getAssetsImages() {
  const images: string[] = []

  // 使用 Vite 的 import.meta.glob 获取所有图片
  const modules = import.meta.glob('/src/assets/**/*.{jpg,jpeg,png,gif,webp,svg}', { eager: true })

  for (const path in modules) {
    const module = modules[path] as { default: string }
    images.push(module.default)
  }

  return images
}
